import { Logger } from '@/utils/log4js';
import {
  ExecutionContext,
  HttpException,
  HttpStatus,
  Injectable,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  canActivate(context: ExecutionContext) {
    // 在这里添加自定义的认证逻辑
    // 例如调用 super.logIn(request) 来建立一个session
    // console.log(context);
    return super.canActivate(context);
    // return true;
  }

  handleRequest(err, user, info) {
    if (info && info.name === 'JsonWebTokenError') {
      Logger.error(`签名已失效`);
      throw new HttpException('签名已失效', HttpStatus.UNAUTHORIZED);
    }
    if (info && info.name === 'TokenExpiredError') {
      Logger.error(`签名已过期`);
      throw new HttpException('签名已过期', HttpStatus.UNAUTHORIZED);
    }
    if (info && info.name === 'Error') {
      Logger.error(`签名已失效`);
      throw new HttpException('签名已失效', HttpStatus.UNAUTHORIZED);
    }
    if (err || !user) {
      Logger.error(`系统异常` + err);
      throw new HttpException('系统异常', HttpStatus.OK);
    }
    return user;
  }
}
